<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-09-28 14:44:40
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\MenuMeta;
use App\Models\Menu;
use Illuminate\Support\Facades\DB;

class MenuRepository extends Repositories
    {
    public function boot(Menu $model)
        {
        $this->model = $model;
        }

    public function getMenuList($menu_ids = null)
        {
        $menu_list = $this->with([
            "meta",
            "children" => function ($query)
                {
                $query->whereHas("meta", function ($query)
                    {
                    $query->whereHidden(0);
                    });
                }
        ])->condition()->whereParent_id(0)->whereHas("meta", function ($query)
            {
            $query->whereHidden(0);
            })->orderBy("sort")->get();
        return $this->removeUnPower($menu_list->toArray(), $menu_ids);
        }

    private function removeUnPower($menu_list, $menu_ids)
        {
        if ($menu_ids == null) {
            return $menu_list;
            }
        $res = [];
        foreach ($menu_list as $v) {
            if ($menu_ids->contains($v['id'])) {
                $v['children'] = $this->removeUnPower($v['children'], $menu_ids);
                $res[]         = $v;
                }
            }
        return $res;
        }
    public function autosave($menu = null, $false = false, $relations = ['details'])
        {
        //排序
        // $this->reSort($menu);
        //设置meta属性
        $menu['meta_id'] = $this->setMeta($menu);
        //设置权限访问
        $this->setApiList($menu);
        if (empty($menu['parent_id']))
            $menu['parent_id'] = 0;
        return $this->setMenu($menu);
        }
    private function setMenu($menu)
        {
        $id   = isset($menu['id']) ? $menu['id'] : 0;
        $menu = $this->model->updateOrCreate(['id' => $id], $menu);
        $menu->meta;
        return $menu;
        }
    private function setApiList(&$menu)
        {
        unset($menu['apiList']);
        }
    private function setMeta(&$menu) : int
        {
        $meta_id = 0;
        if (isset($menu['meta'])) {
            $id      = isset($menu['meta']['id']) ? $menu['meta']['id'] : 0;
            $meta    = MenuMeta::updateOrCreate(['id' => $id], $menu['meta']);
            $meta_id = $meta->id;
            unset($menu['meta']);
            }
        return $meta_id;
        }

    public function delete($ids)
        {
        return $this->with(['meta'])->whereIn("id", $ids)->autodelete();
        }

    public function role($menu_id)
        {
        return $this->model->whereId($menu_id)->get()->role;
        }
    }